package top.ooyyh.bytheway.interceptor;

import cn.hutool.json.JSONObject;
import io.jsonwebtoken.Claims;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import top.ooyyh.bytheway.annotation.AuthRequired;
import top.ooyyh.bytheway.utils.JwtUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        // 检查方法或类上是否有AuthRequired注解
        AuthRequired authRequired = method.getAnnotation(AuthRequired.class);
        if (authRequired == null) {
            authRequired = method.getDeclaringClass().getAnnotation(AuthRequired.class);
        }

        // 如果没有注解，直接通过
        if (authRequired == null) {
            return true;
        }
        JSONObject result = new JSONObject();
        // 从header中获取token
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            result.set("message","未提供认证token");
            result.set("code",401);
            response.getWriter().write(result.toJSONString(0));
            response.getWriter().flush();
            //response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        // 验证token并获取用户权限(这里需要实现你的token验证逻辑)
        Claims userInfo = verifyToken(token);
        if (userInfo == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            result.set("message","无效token");
            result.set("code",401);
            response.getWriter().write(result.toJSONString(0));
            response.getWriter().flush();
            return false;
        }

        // 检查权限
        String[] requiredPermissions = authRequired.permissions();
        if (requiredPermissions.length > 0) {
            for (String permission : requiredPermissions) {
                if (!userInfo.get("role").equals(permission) ) {
                    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    response.setContentType("application/json;charset=UTF-8");
                    result.set("message","权限不足");
                    result.set("code",403);
                    response.getWriter().write(result.toJSONString(0));
                    response.getWriter().flush();
                    return false;
                }
            }
        }

        // 将用户信息存入request，方便后续使用
        request.setAttribute("currentUser", userInfo);
        return true;
    }

    private Claims verifyToken(String token) {
        if (!JwtUtils.validateToken(token)){
            return null;
        }
        return JwtUtils.parseToken(token);
    }
}
